﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using FrienDev.Data;

namespace FrienDev.BusinessRules
{
    public class MessageRules
    {
        public static MessageRules Instance = new MessageRules();

        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private MessageRules()
        {
        }

        /// <summary>
        /// 获取短消息数量
        /// </summary>
        public int GetCurrentUserMessageCount()
        {
            int sm = (from c in m_DataContext.Messages
                      where c.ReceiverId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 0 && c.IsRead == false                
                      select c).Count();
            return sm;
        }

        /// <summary>
        /// 获取系统消息数量
        /// </summary>
        /// <param name="UserId"></param>
        public int GetCurrentUserSystemMessageCount()
        {
            int ssm = (from c in m_DataContext.Messages
                       where c.ReceiverId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 1 && c.IsRead == false 
                       select c).Count();
            return ssm;
        }

        public IEnumerable<Message> GetCurrentUserSendMessage()
        {
            IEnumerable<Message> temp = from c in m_DataContext.Messages
                                        where c.SenderId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 0 
                                        orderby c.SendDateTime
                                        select c;
            return temp;
         }

        /// <summary>
        /// 取得消息中心的数据源（收件）
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<Message> GetCurrentUserMessages()
        {
            
            var temp = from c in m_DataContext.Messages
                       where c.ReceiverId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 0 
                       orderby c.SendDateTime descending
                       group c by c.ParentId into g
                       select g;
            //var a = temp.ToList();
            List<Message> messages = new List<Message>();
            foreach (var item in temp)
            {
                messages.Add(item.First());
            }
            
            return messages.Reverse<Message>().ToList<Message>();
                                   
            
        }

        /// <summary>
        /// 取得消息中心的数据源
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<Message> GetCurrentUserMessagesForMessageCenter()
        {

            var temp = from c in m_DataContext.Messages
                       where c.ReceiverId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 0 && c.IsRead == false 
                       orderby c.SendDateTime descending
                       group c by c.ParentId into g
                       select g;
            //var a = temp.ToList();
            List<Message> messages = new List<Message>();
            foreach (var item in temp)
            {
                messages.Add(item.First());
            }
            return messages;


        }

        
        /// <summary>
        /// 取得系统消息的数据源
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<Message> GetCurrentUserSystemMessages()
        {
            IEnumerable<Message> sysmessages = from c in m_DataContext.Messages
                                 where c.ReceiverId == UserRules.Instance.GetCurrentUserId() && c.MessageType == 1 
                                 orderby c.SendDateTime descending
                                 select c;
            return sysmessages.ToList<Message>();
        }

        

        /// <summary>
        /// 生成系统消息内容的方法
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        private string GetSystemContent(Message c)
        {
            throw new NotImplementedException();
        }
        
        /// <summary>
        /// 取得会话数量
        /// </summary>
        /// <param name="SenderId"></param>
        /// <returns></returns>
        public int GetCurrentUserMessageSessionCount(string messageId)
        {
            int msgId = int.Parse(messageId);
            Message msg = GetMessageObjectByMessageId(msgId);
            IEnumerable<Message> currentMsg = (from c in m_DataContext.Messages
                                               where c.MessageId == msgId
                                               select c).Union(
                                              from d in m_DataContext.Messages
                                              where d.ParentId == msg.ParentId
                                              select d);
            return currentMsg.Count<Message>();
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="messageId"></param>
        public void DeleteMessageByMessageId(string messageId)
        {
            int currentMessageId = int.Parse(messageId);
            Message curMsg = GetMessageObjectByMessageId(currentMessageId);
            m_DataContext.Messages.DeleteOnSubmit(curMsg);
            m_DataContext.SubmitChanges();
             
        }

        public void SignReadMessageByMessageId(string messageId)
        {
            int currentMessageId = int.Parse(messageId);
            Message curMsg = GetMessageObjectByMessageId(currentMessageId);
            curMsg.IsRead = true;
            m_DataContext.SubmitChanges();
        }

        public void SignReadSystemMessage()
        {
            IList<Message> msgs = GetCurrentUserSystemMessages();
            for (int i = 0; i < msgs.Count; i++)
            {
                Message curMsg = GetMessageObjectByMessageId(msgs[i].MessageId);
                curMsg.IsRead = true;
            }
            m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 删除当前用户的所有系统消息
        /// </summary>
        public void DeleteCurrentUserSystemMessage()
        {
            IEnumerable<Message> temp = GetCurrentUserSystemMessages();
            foreach(Message singleMsg in temp)
            {
                DeleteMessageByMessageId(singleMsg.MessageId.ToString());
            }
        }

        /// <summary>
        /// 取得消息对象
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public Message GetMessageObjectByMessageId(int messageId)
        {
            IEnumerable<Message> currentMsg = from c in m_DataContext.Messages
                                 where c.MessageId == messageId
                                 select c;
            if (currentMsg.Count<Message>() > 0)
            {
                return currentMsg.First<Message>();
            }
            else
                return null;
        }

        /// <summary>
        /// 变更系统消息类别
        /// </summary>
        /// <param name="messageId"></param>
        /// <param name="targetType"></param>
        public void ChangeSystemMessageRequestType(int messageId,string targetType)
        {
            Message msg = GetMessageObjectByMessageId(messageId);
            string content = msg.MessageContent;
            string[] tempcontent = content.Split(new string[] { "#####" }, StringSplitOptions.None);
            tempcontent[1] = targetType;
            StringBuilder sbFinalContent = new StringBuilder();
            string finalContent;
            for (int i = 0; i < tempcontent.Length; i++)
            {
                sbFinalContent.Append(tempcontent[i]);
                if (i < tempcontent.Length - 1)
                {
                    sbFinalContent.Append("#####");
                }
            }
            finalContent = sbFinalContent.ToString();
            msg.MessageContent = finalContent;
            m_DataContext.SubmitChanges();

             
        }
        /// <summary>
        /// 发送消息，往数据库中插入相应记录
        /// </summary>
        /// <param name="Receiver"></param>
        /// <param name="Content"></param>
        public void SendMessage(string[] Receiver, string Content)
        {
            for (int i = 0; i < Receiver.Length; i++)
            {
                var msg = new Message
                {
                    MessageType = 0,
                    MessageContent = Content,
                    SendDateTime = DateTime.Now,
                    SenderId = UserRules.Instance.GetCurrentUserId(),
                    ReceiverId = UserRules.Instance.GetUserIdByUserName(Receiver[i]),
                    IsRead = false
                };
                if (!string.IsNullOrEmpty(msg.ReceiverId))
                {
                    m_DataContext.Messages.InsertOnSubmit(msg);
                    m_DataContext.SubmitChanges(); 
                    int m_ParentId = msg.MessageId;
                    msg.ParentId = m_ParentId;
                }
       
            }
            m_DataContext.SubmitChanges(); 
            
        }

        /// <summary>
        /// 发送系统消息
        /// </summary>
        /// <param name="Receiver"></param>
        /// <param name="Content"></param>
        public void SendSystemMessage(DateTime SendDateTime,string ReceiverId, string Content)
        {
            var msg = new Message
            {
                MessageType = 1,
                MessageContent = Content,
                SendDateTime = SendDateTime,
                SenderId = null,
                ReceiverId = ReceiverId,
                IsRead = false
            };
            m_DataContext.Messages.InsertOnSubmit(msg);
            m_DataContext.SubmitChanges(); 
        }

        /// <summary>
        /// 回复消息，往数据库中插入相应记录
        /// </summary>
        /// <param name="Receiver"></param>
        /// <param name="Content"></param>
        public void ReplyMessage(string RecId, string Content,string ParentId)
        {
                var msg = new Message
                {
                    MessageType = 0,
                    MessageContent = Content,
                    SendDateTime = DateTime.Now,
                    SenderId = UserRules.Instance.GetCurrentUserId(),
                    ReceiverId = RecId,
                    IsRead = false,
                    ParentId=int.Parse(ParentId)
                };
                m_DataContext.Messages.InsertOnSubmit(msg);
                m_DataContext.SubmitChanges();
        }

        /// <summary>
        /// 返回查看接收信息的地址
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public string ViewReceivedMessageUrl(string messageId)
        {
            return "/Home/ReceiveMessageDetails.aspx?messageid=" + messageId;
        }

        /// <summary>
        /// 返回回复的地址
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public string ReplyReceivedMessageUrl(string messageId)
        {
            return "/Home/ReceiveMessageDetails.aspx?messageid=" + messageId+"#replyarea";
        }

        /// <summary>
        /// 返回发送消息的地址
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public string ViewSendMessageUrl(string messageId)
        {
            return "/Home/ReceiveMessageDetails.aspx?messageid=" + messageId + "#replyarea";
        }

        /// <summary>
        /// 为接收消息详细页面取得相应的消息列表
        /// </summary>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public IEnumerable<Message> GetCurrentUserAssMessage(string messageId)
        {
            
            int msgId = int.Parse(messageId);
            Message msg=GetMessageObjectByMessageId(msgId);
            IEnumerable<Message> currentMsg = (from c in m_DataContext.Messages
                                               where c.MessageId == msgId
                                               select c).Union(
                                              from d in m_DataContext.Messages
                                              where d.ParentId ==msg.ParentId
                                              select d);
            return currentMsg;
        }

        public string GetReplyReceiverUserId(string messageId)
        {
            int msgId = int.Parse(messageId);
            IEnumerable<Message> currentMsg = from c in m_DataContext.Messages
                                              where c.MessageId == msgId
                                              select c;
            return currentMsg.First<Message>().SenderId;
        }

        /// <summary>
        /// 删除会话消息
        /// </summary>
        /// <param name="messageId"></param>
        public void DeleteSessionMessageByMessageId(string messageId)
        {
            int msgId = int.Parse(messageId);
            Message msg = GetMessageObjectByMessageId(msgId);
            IEnumerable<Message> currentMsg = (from c in m_DataContext.Messages
                                               where c.MessageId == msgId
                                               select c).Union(
                                              from d in m_DataContext.Messages
                                              where d.ParentId == msg.ParentId
                                              select d);
            if (currentMsg.Count<Message>() == 1)
            {
                DeleteMessageByMessageId(currentMsg.ElementAt<Message>(0).MessageId.ToString());
                return;
            }
            for (int i = currentMsg.Count<Message>() - 1; i > 0; i--)
            {
                DeleteMessageByMessageId(currentMsg.ElementAt<Message>(i).MessageId.ToString());
            }
            //foreach (Message scurMessage in currentMsg)
            //{
            //    DeleteMessageByMessageId(scurMessage.MessageId.ToString());
            //}

        }
    }
}
